import { z } from 'zod';

/**
 * 标准API响应格式
 */
export const ApiResponseSchema = z.object({
  success: z.boolean(),
  data: z.any().optional(),
  error: z.object({
    code: z.string(),
    message: z.string(),
    details: z.any().optional()
  }).optional(),
  meta: z.object({
    timestamp: z.string(),
    requestId: z.string().optional(),
    version: z.string().optional()
  })
});

export type ApiResponse<T = any> = z.infer<typeof ApiResponseSchema> & {
  data?: T;
};

/**
 * MCP消息Schema定义
 */
export const MCPMessageSchema = z.object({
  id: z.string().uuid({ message: "无效的UUID格式" }),
  type: z.string().min(1).max(100),
  payload: z.record(z.string(), z.any()),
  headers: z.record(z.string(), z.string()).default({}),
  timestamp: z.string().datetime({ message: "无效的日期时间格式" }).default(() => new Date().toISOString()),
  source: z.string().optional(),
  priority: z.enum(['low', 'medium', 'high', 'critical']).default('medium'),
  ttl: z.number().int().positive().optional(), // Time to live in seconds
  retryCount: z.number().int().min(0).default(0),
  maxRetries: z.number().int().min(0).default(3)
});

export type MCPMessage = z.infer<typeof MCPMessageSchema>;

/**
 * 消息路由规则Schema
 */
export const RouteRuleSchema = z.object({
  id: z.string().uuid({ message: "无效的UUID格式" }),
  name: z.string().min(1).max(100),
  description: z.string().max(500).optional(),
  enabled: z.boolean().default(true),
  condition: z.object({
    type: z.string().optional(),
    source: z.string().optional(),
    headers: z.record(z.string(), z.string()).optional(),
    payload: z.record(z.string(), z.any()).optional(),
    priority: z.array(z.enum(['low', 'medium', 'high', 'critical'])).optional()
  }),
  target: z.object({
    type: z.enum(['webhook', 'queue', 'database', 'ai', 'custom']),
    config: z.record(z.string(), z.any())
  }),
  createdAt: z.string().datetime({ message: "无效的日期时间格式" }).default(() => new Date().toISOString()),
  updatedAt: z.string().datetime({ message: "无效的日期时间格式" }).default(() => new Date().toISOString())
});

export type RouteRule = z.infer<typeof RouteRuleSchema>;

/**
 * 健康检查响应Schema
 */
export const HealthCheckSchema = z.object({
  status: z.enum(['healthy', 'degraded', 'unhealthy']),
  timestamp: z.string().datetime({ message: "无效的日期时间格式" }),
  version: z.string(),
  services: z.record(z.string(), z.object({
    status: z.enum(['up', 'down', 'degraded']),
    responseTime: z.number().optional(),
    error: z.string().optional()
  })),
  uptime: z.number(),
  memory: z.object({
    used: z.number(),
    total: z.number(),
    percentage: z.number()
  }),
  system: z.object({
    platform: z.string(),
    nodeVersion: z.string(),
    pid: z.number()
  })
});

export type HealthCheck = z.infer<typeof HealthCheckSchema>;

/**
 * 包装在标准响应中的健康检查响应Schema
 */
export const DetailedHealthCheckResponseSchema = ApiResponseSchema.extend({
  data: HealthCheckSchema
});


/**
 * 分页请求参数Schema
 */
export const PaginationSchema = z.object({
  page: z.number().int().positive().default(1),
  limit: z.number().int().positive().max(100).default(20),
  sortBy: z.string().optional(),
  sortOrder: z.enum(['asc', 'desc']).default('desc')
});

export type PaginationQuery = z.infer<typeof PaginationSchema>;

/**
 * 分页响应Schema
 */
export const PaginatedResponseSchema = <T>(itemSchema: z.ZodType<T>) =>
  z.object({
    items: z.array(itemSchema),
    pagination: z.object({
      page: z.number().int().positive(),
      limit: z.number().int().positive(),
      total: z.number().int().min(0),
      pages: z.number().int().min(0),
      hasNext: z.boolean(),
      hasPrev: z.boolean()
    })
  });

/**
 * 错误代码枚举
 */
export enum ErrorCode {
  // 通用错误
  INTERNAL_ERROR = 'INTERNAL_ERROR',
  VALIDATION_ERROR = 'VALIDATION_ERROR',
  NOT_FOUND = 'NOT_FOUND',
  UNAUTHORIZED = 'UNAUTHORIZED',
  FORBIDDEN = 'FORBIDDEN',
  RATE_LIMIT_EXCEEDED = 'RATE_LIMIT_EXCEEDED',

  // MCP特定错误
  MESSAGE_INVALID = 'MESSAGE_INVALID',
  MESSAGE_PROCESSING_FAILED = 'MESSAGE_PROCESSING_FAILED',
  MESSAGE_ROUTING_FAILED = 'MESSAGE_ROUTING_FAILED',
  MESSAGE_DELIVERY_FAILED = 'MESSAGE_DELIVERY_FAILED',
  ROUTE_RULE_NOT_FOUND = 'ROUTE_RULE_NOT_FOUND',
  ROUTE_RULE_INVALID = 'ROUTE_RULE_INVALID',

  // 服务错误
  DATABASE_ERROR = 'DATABASE_ERROR',
  EXTERNAL_SERVICE_ERROR = 'EXTERNAL_SERVICE_ERROR',
  TIMEOUT_ERROR = 'TIMEOUT_ERROR'
}

/**
 * 创建标准API响应的帮助函数
 */
export class ApiResponseBuilder {
  /**
   * 创建成功响应
   */
  static success<T>(data: T, meta?: Partial<ApiResponse['meta']>): ApiResponse<T> {
    return {
      success: true,
      data,
      meta: {
        timestamp: new Date().toISOString(),
        ...meta
      }
    };
  }

  /**
   * 创建错误响应
   */
  static error(
    code: ErrorCode,
    message: string,
    details?: any,
    meta?: Partial<ApiResponse['meta']>
  ): ApiResponse {
    return {
      success: false,
      error: {
        code,
        message,
        details
      },
      meta: {
        timestamp: new Date().toISOString(),
        ...meta
      }
    };
  }

  /**
   * 创建分页响应
   */
  static paginated<T>(
    items: T[],
    pagination: {
      page: number;
      limit: number;
      total: number;
    },
    meta?: Partial<ApiResponse['meta']>
  ) {
    const pages = Math.ceil(pagination.total / pagination.limit);

    return this.success({
      items,
      pagination: {
        ...pagination,
        pages,
        hasNext: pagination.page < pages,
        hasPrev: pagination.page > 1
      }
    }, meta);
  }
}
